<template>
  <el-button type="primary" @click="addGroupDialog = true">新增题组</el-button>
  <el-dialog v-model="addGroupDialog" title="新增题组" width="350px">
    <el-form :model="form" label-width="80px" :rules="rules" ref="formRef">
      <el-form-item label="题组名称" prop="groupName">
        <el-input v-model="form.groupName"></el-input>
      </el-form-item>
      <el-form-item label="题组类型" prop="questionTypeId">
        <el-select v-model="form.questionTypeId" placeholder="请选择题组类型">
          <el-option v-for="(type,index) in types" :key="index" :label="type.typeName"
                     :value="type.questionTypeId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" :rows="2" type="textarea" placeholder="请输入备注"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addGroupDialog = false">取消</el-button>
        <el-button type="primary" @click="doSubmit(formRef)" :loading="loading">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { inject, reactive, ref } from 'vue'
import { ElForm, ElMessage } from 'element-plus'
import { addGroup, typeList } from '@/api/admin'

const reload: any = inject('reload')
const loading = ref<boolean>(false)
const addGroupDialog = ref<boolean>(false)
const form = reactive({
  groupName: '',
  questionTypeId: null,
  remark: ''
})
const rules = {
  groupName: [{
    required: true,
    message: '请输入题组名称',
    trigger: 'change'
  }],
  questionTypeId: [{
    required: true,
    message: '请选择题组类型',
    trigger: 'change'
  }],
  remark: [{
    required: false
  }]
}
type FormInstance = InstanceType<typeof ElForm>
const formRef = ref<FormInstance>()
const doSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      loading.value = true
      addGroup(form.groupName, form.questionTypeId, form.remark).then(() => {
        ElMessage.success('新增成功')
        addGroupDialog.value = false
        reload()
      }).finally(() => {
        loading.value = false
      })
    } else {
      return false
    }
  })
}
const types = ref(null)
typeList().then(resp => {
  types.value = resp.data.data
})
</script>

<style scoped>

</style>
